package com.boot.security.server.controller.mffl.MfflChatContent;

import com.boot.security.server.dao.mffl.*;
import com.boot.security.server.model.FileInfo;
import com.boot.security.server.model.SysUser;
import com.boot.security.server.model.mffl.*;
import com.boot.security.server.model.mffl.Vo.MfflChatContentVo;
import com.boot.security.server.model.mffl.Vo.MfflMappingVo;
import com.boot.security.server.model.mffl.Vo.MfflSystemMessagesCountVo;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableHandler.CountHandler;
import com.boot.security.server.page.table.PageTableHandler.ListHandler;
import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.service.FileService;
import com.boot.security.server.service.impl.mffl.MfflChatContent.MfflChatContentService;
import com.boot.security.server.utils.UserUtil;
import com.boot.security.server.utils.mffl.JPush.JPushUtil;
import com.boot.security.server.utils.mffl.MfflUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Api(tags = "即时通讯接口")
@RestController
@RequestMapping("/client/mfflChatContents")
public class Client_MfflChatContentController {

    @Autowired
    private MfflChatContentDao mfflChatContentDao;

    @Autowired
    private MfflUserDao mfflUserDao;

    @Autowired
    private FileService fileService;

    @Autowired
    private MfflMappingDao mfflMappingDao;

    @Autowired
    private MfflSystemMessagesDao mfflSystemMessagesDao;

    @Autowired
    private MfflChatContentService mfflChatContentService;

    @PostMapping("/sendMessageText")
    @ApiOperation(value = "图文咨询-发送消息(文字类)")
    public ReturnBean save(@ApiParam(value = "接收人userid", name = "receiveId", required = true) @RequestParam int receiveId,
                           @ApiParam(value = "内容", name = "content", required = true) @RequestParam String content) {

        SysUser sysUser = UserUtil.getLoginUser();
        MfflUser startUser = this.mfflUserDao.getUserInfoAll(sysUser.getId().intValue());
        if (startUser.getIdentity() == 1 && startUser.getLawyerInspect() != 1) {
            return new ReturnBean("201", "该律师为未认证或重新修改认证信息暂不可聊天");
        }
        return mfflChatContentService.sendMessage(sysUser.getId().intValue(), receiveId, content);
    }

    @PostMapping("/sendMessageImg")
    @ApiOperation(value = "图文咨询-发送消息(图片类)")
    public ReturnBean sendMessageImg(@ApiParam(value = "接收人userid", name = "receiveId", required = true) @RequestParam int receiveId,
                                     @ApiParam(value = "内容", name = "file", required = true) @RequestParam MultipartFile file) throws IOException {

        SysUser sysUser = UserUtil.getLoginUser();
        MfflUser startUser = this.mfflUserDao.getUserInfoAll(sysUser.getId().intValue());
        if (startUser.getIdentity() == 1 && startUser.getLawyerInspect() != 1) {
            return new ReturnBean("201", "该律师为未认证或重新修改认证信息暂不可聊天");
        }

        MfflUser receiveUser = this.mfflUserDao.getUserInfoAll(receiveId);
        if (receiveUser == null) {
            return new ReturnBean("201", "用户不存在");
        }
        if (file == null) {
            return new ReturnBean("201", "请输入内容");
        }

        if (receiveUser.getIdentity() == 1 && receiveUser.getLawyerInspect() != 1) {
            return new ReturnBean("201", "该律师为未认证或重新修改认证信息暂不可聊天");
        }

        MfflMapping mfflMapping = this.mfflMappingDao.getMfflMappingByUserIdAndLawyerId(sysUser.getId(), Long.valueOf(receiveId));
        if (mfflMapping == null) {
            return new ReturnBean("201", "聊天关系不存在");
        }
        if (mfflMapping.getFirstTime() <= 0) {
            return new ReturnBean("201", "聊天时间已到不能聊天");
        }

        FileInfo fileInfo = this.fileService.save(file);
        fileInfo = this.fileService.chatImgSave(fileInfo);

        MfflChatContent mfflChatContent = new MfflChatContent();
        mfflChatContent.setSendId(sysUser.getId().intValue());
        mfflChatContent.setReceiveId(receiveId);
        mfflChatContent.setContent(fileInfo.getUrl());
        mfflChatContent.setMappingId(mfflMapping.getId().intValue());
        mfflChatContent.setState(1);
        int status = this.mfflChatContentDao.save(mfflChatContent);
        if (status == 0) {
            return new ReturnBean("201", "发送失败");
        }
        if (!StringUtils.isEmpty(receiveUser.getJpush())) {
            if (receiveUser.getIdentity() == 0) {
                JPushUtil.pushMsg(receiveUser.getJpush(), "法智消息", "您收到一张图片!");
            } else if (receiveUser.getIdentity() == 1) {
                JPushUtil.pushMsgLawyer(receiveUser.getJpush(), "法智消息", "您收到一张图片");
            }
        }
        this.mfflMappingDao.updateContent("[图片]", mfflMapping.getId());

        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(fileInfo.getUrl());
        return returnBean;
    }

    @PostMapping("/sendMessageMP3")
    @ApiOperation(value = "图文咨询-发送消息(语音类)")
    public ReturnBean sendMessageMP3(@ApiParam(value = "接收人userid", name = "receiveId", required = true) @RequestParam int receiveId,
                                     @ApiParam(value = "内容", name = "file", required = true) @RequestParam MultipartFile file) throws IOException {

        SysUser sysUser = UserUtil.getLoginUser();
        MfflUser startUser = this.mfflUserDao.getUserInfoAll(sysUser.getId().intValue());
        if (startUser.getIdentity() == 1 && startUser.getLawyerInspect() != 1) {
            return new ReturnBean("201", "该律师为未认证或重新修改认证信息暂不可聊天");
        }

        MfflUser receiveUser = this.mfflUserDao.getUserInfoAll(receiveId);
        if (receiveUser == null) {
            return new ReturnBean("201", "用户不存在");
        }
        if (file == null) {
            return new ReturnBean("201", "请输入内容");
        }

        if (receiveUser.getIdentity() == 1 && receiveUser.getLawyerInspect() != 1) {
            return new ReturnBean("201", "该律师为未认证或重新修改认证信息暂不可聊天");
        }

        MfflMapping mfflMapping = this.mfflMappingDao.getMfflMappingByUserIdAndLawyerId(sysUser.getId(), Long.valueOf(receiveId));
        if (mfflMapping == null) {
            return new ReturnBean("201", "聊天关系不存在");
        }
        if (mfflMapping.getFirstTime() <= 0) {
            return new ReturnBean("201", "聊天时间已到不能聊天");
        }
        String fileOrigName = file.getOriginalFilename();
        int st = fileOrigName.indexOf(".");
        String suffix = fileOrigName.substring(st);
        if (!suffix.equals(".mp3") && !suffix.equals(".amr")) {
            return new ReturnBean("201", "语音格式错误");
        }
        FileInfo fileInfo = this.fileService.save(file);

        MfflChatContent mfflChatContent = new MfflChatContent();
        mfflChatContent.setSendId(sysUser.getId().intValue());
        mfflChatContent.setReceiveId(receiveId);
        mfflChatContent.setContent(fileInfo.getUrl());
        mfflChatContent.setMappingId(mfflMapping.getId().intValue());
        mfflChatContent.setState(2);
        int status = this.mfflChatContentDao.save(mfflChatContent);
        if (status == 0) {
            return new ReturnBean("201", "发送失败");
        }
        if (!StringUtils.isEmpty(receiveUser.getJpush())) {
            if (receiveUser.getIdentity() == 0) {
                JPushUtil.pushMsg(receiveUser.getJpush(), "法智消息", "您收到一段语音!");
            } else if (receiveUser.getIdentity() == 1) {
                JPushUtil.pushMsgLawyer(receiveUser.getJpush(), "法智消息", "您收到一段语音");
            }
        }
        this.mfflMappingDao.updateContent("[语音]", mfflMapping.getId());

        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(fileInfo.getUrl());
        return returnBean;
    }


    @GetMapping(value = "/getChatRecord")
    @ApiOperation(value = "图文咨询-获取聊天记录")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "offset", value = "开始条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "limit", value = "每页条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "receiveId", value = "接收人userid", paramType = "query", dataType = "int")})
    public ReturnBean<MfflChatContentVo> list(PageTableRequest request) {

        if (request.getParams().get("receiveId") == null) {
            return new ReturnBean("201", "参数错误，接收人不可为空");
        }
        SysUser sysUser = UserUtil.getLoginUser();
        MfflMapping mfflMapping = this.mfflMappingDao.getMfflMappingByUserIdAndLawyerId(sysUser.getId(), Long.valueOf(request.getParams().get("receiveId").toString()));
        long id = 0;
        if (mfflMapping == null) {
            //添加聊天关系
            id = mfflChatContentService.addMapping(Integer.parseInt(request.getParams().get("receiveId").toString()), sysUser.getId().intValue());
        } else {
            id = mfflMapping.getId();
        }

        //查询聊天记录
        request.getParams().put("sendId", sysUser.getId());
        PageTableResponse tableResponse = new PageTableHandler(new CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return mfflChatContentDao.getChatRecordCount(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<MfflChatContentVo> list(PageTableRequest request) {
                return mfflChatContentDao.getChatRecordList(request.getParams(), request.getOffset(), request.getLimit());
            }
        }).handle(request);
        List<MfflChatContentVo> mfflChatContentVoList = (List<MfflChatContentVo>) tableResponse.getData();
        for (MfflChatContentVo m : mfflChatContentVoList) {
            if (m.getSendId().longValue() == sysUser.getId()) {
                m.setChatStatus(0);
            } else {
                m.setChatStatus(1);
            }
            if (m.getState() == 1) {
                m.setMasterMap(m.getContent().replaceAll("_chat", ""));
            }
        }

        this.mfflChatContentDao.updateStatus(id);

        if (mfflChatContentVoList.size() != 0) {
            this.mfflMappingDao.updateMappingContentStatus(mfflChatContentVoList.get(0).getMappingId());
        }
        MfflMapping mfflMappingVo = this.mfflMappingDao.getById(id);
        tableResponse.setFirstTime(mfflMappingVo.getFirstTime());
        Collections.reverse(mfflChatContentVoList);
        tableResponse.setData(mfflChatContentVoList);
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(tableResponse);
        return returnBean;
    }


    @PostMapping(value = "/setStartTime")
    @ApiOperation(value = "图文咨询--获取聊天记录前先触发这个接口")
    public ReturnBean<MfflMappingVo> setStartTime(@ApiParam(value = "接收人userid", name = "receiveId", required = true) @RequestParam int receiveId) {
        SysUser sysUser = UserUtil.getLoginUser();
        if (sysUser == null) {
            return new ReturnBean("201", "没有此用户");
        }

        if (sysUser.getId() == receiveId) {
            return new ReturnBean("201", "不可与自己聊天");
        }

        Date date = new Date();
        MfflUser user = this.mfflUserDao.getUserInfoAll(sysUser.getId().intValue());
        //判断聊天关系并处理
        MfflMappingVo mfflMapping = this.mfflMappingDao.getMfflMappingByUserIdAndLawyerId(sysUser.getId(), Long.valueOf(receiveId));
        if (mfflMapping == null) {
            //添加聊天关系
            mfflChatContentService.addMapping(user.getIdentity() == 0 ? user.getId().intValue() : receiveId, user.getIdentity() == 1 ? user.getId().intValue() : receiveId);
        } else {
            if (mfflMapping.getEndTime() == null) {
                if (mfflMapping.getStartTime() != null) {
                    long time = date.getTime() / 1000 - mfflMapping.getStartTime().getTime() / 1000;
                    int firstTime = mfflMapping.getFirstTime() - (int) time;
                    this.mfflMappingDao.updateFirstTime(mfflMapping.getId(), firstTime < 0 ? 0 : firstTime, date);
                } else {
                    this.mfflMappingDao.updateFirstTimeStart(mfflMapping.getId(), date);
                }

            } else {
                this.mfflMappingDao.updateFirstTimeStart(mfflMapping.getId(), date);
            }
        }

        MfflMappingVo mfflMappingVo = this.mfflMappingDao.getMfflMappingByUserIdAndLawyerId(sysUser.getId(), Long.valueOf(receiveId));
        mfflMappingVo.setTimeRemaining(MfflUtil.secondToTime(mfflMappingVo.getFirstTime()));
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(mfflMappingVo);
        return returnBean;
    }

    @PostMapping(value = "/setEndTime")
    @ApiOperation(value = "图文咨询--聊天窗口关闭后触发这个接口")
    public ReturnBean<MfflMappingVo> setEndTime(@ApiParam(value = "接收人userid", name = "receiveId", required = true) @RequestParam int receiveId) {
        SysUser sysUser = UserUtil.getLoginUser();
        if (sysUser == null) {
            return new ReturnBean("201", "没有此用户");
        }
        if (sysUser.getId() == receiveId) {
            return new ReturnBean("201", "不可与自己聊天");
        }

        Date date = new Date();
        //判断聊天关系并处理
        MfflMapping mfflMapping = this.mfflMappingDao.getMfflMappingByUserIdAndLawyerId(sysUser.getId(), Long.valueOf(receiveId));
        if (mfflMapping == null) {
            return new ReturnBean("201", "聊天关系不存在");
        } else {
            if (mfflMapping.getEndTime() == null) {
                if (mfflMapping.getStartTime() != null) {
                    long time = date.getTime() / 1000 - mfflMapping.getStartTime().getTime() / 1000;
                    int firstTime = mfflMapping.getFirstTime() - (int) time;
                    this.mfflMappingDao.updateFirstTime(mfflMapping.getId(), firstTime < 0 ? 0 : firstTime, date);
                } else {
                    this.mfflMappingDao.updateFirstTimeStart(mfflMapping.getId(), date);
                }

            } else {
                this.mfflMappingDao.updateFirstTimeStart(mfflMapping.getId(), date);
            }
        }
        return new ReturnBean();
    }


    @GetMapping(value = "/getMyMessage")
    @ApiOperation(value = "消息中心-消息列表")
    public ReturnBean<MfflChatContentVo> getMessage() {
        SysUser sysUser = UserUtil.getLoginUser();
        if (sysUser == null) {
            return new ReturnBean("201", "没有此用户");
        }
        MfflUser mfflUser = this.mfflUserDao.getUserInfoAll(sysUser.getId().intValue());
        String where = "";
        List<MfflMappingVo> mfflMappingVoList = new ArrayList<>();
        if (mfflUser.getIdentity() == 0) {
            where = "mm.user_id";
            mfflMappingVoList = this.mfflMappingDao.getMyMessageList(where, mfflUser.getUserid());
        } else {
            where = "mm.lawyer_id";
            mfflMappingVoList = this.mfflMappingDao.getMyMessageListLaywer(where, mfflUser.getUserid());
        }
        List<MfflChatContentVo> mfflChatContentVoList = new ArrayList<>();
        for (MfflMappingVo m : mfflMappingVoList) {

            MfflChatContentVo mfflChatContentVo = new MfflChatContentVo();
            if (mfflUser.getIdentity() == 0) {
                mfflChatContentVo.setSendId(m.getLawyerId());
            } else {
                mfflChatContentVo.setSendId(m.getUserId());
            }
            mfflChatContentVo.setContent(m.getContent());
            mfflChatContentVo.setCreateTime(m.getFinallyTime());
            mfflChatContentVo.setStatus(m.getStatus());
            mfflChatContentVo.setNickname(m.getNickname());
            mfflChatContentVo.setHeadImgUrl(m.getHeadImgUrl());
            if (mfflUser.getIdentity() == 0) {
                mfflChatContentVo.setChatCount(mfflChatContentDao.getChatCountByMappingId(m.getLawyerId(),m.getUserId()));
            }else {
                mfflChatContentVo.setChatCount(mfflChatContentDao.getChatCountByMappingId(m.getUserId(),m.getLawyerId()));
            }


            mfflChatContentVoList.add(mfflChatContentVo);
        }
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(mfflChatContentVoList);

        return returnBean;
    }


    @GetMapping(value = "/getSystemMessages")
    @ApiOperation(value = "消息中心-系统消息")
    public ReturnBean<MfflSystemMessages> getSystemMessages() {
        SysUser sysUser = UserUtil.getLoginUser();
        if (sysUser == null) {
            return new ReturnBean("201", "没有此用户");
        }
        List<MfflSystemMessages> mfflSystemMessagesList = this.mfflSystemMessagesDao.getSystemMessages(sysUser.getId());
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(mfflSystemMessagesList);
        return returnBean;
    }


    @GetMapping(value = "/getSystemMessagesCount")
    @ApiOperation(value = "消息中心-系统消息数量和消息状态")
    public ReturnBean<MfflSystemMessagesCountVo> getSystemMessagesCount() {
        SysUser sysUser = UserUtil.getLoginUser();
        if (sysUser == null) {
            return new ReturnBean("201", "没有此用户");
        }
        MfflSystemMessagesCountVo mfflSystemMessagesList = this.mfflSystemMessagesDao.getSystemMessagesCount(sysUser.getId());
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(mfflSystemMessagesList);
        return returnBean;
    }


    @GetMapping(value = "/getSystemMessagesLimit")
    @ApiOperation(value = "消息中心-系统消息分页")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "offset", value = "开始条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "limit", value = "每页条数", dataType = "int")})
    public ReturnBean<MfflSystemMessages> getSystemMessagesLimit(PageTableRequest request) {
        SysUser sysUser = UserUtil.getLoginUser();
        if (sysUser == null) {
            return new ReturnBean("201", "没有此用户");
        }
        if (request.getOffset() == null) {
            return new ReturnBean("201", "offset错误");
        }
        if (request.getLimit() == null) {
            return new ReturnBean("201", "limit错误");
        }
        request.getParams().put("userId", sysUser.getId());
        request.getParams().put("orderBy", "order by createTime desc");

        PageTableResponse tableResponse = new PageTableHandler(new CountHandler() {

            @Override
            public int count(PageTableRequest request) {
                return mfflSystemMessagesDao.count(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<MfflSystemMessages> list(PageTableRequest request) {
                return mfflSystemMessagesDao.list(request.getParams(), request.getOffset(), request.getLimit());
            }
        }).handle(request);

        List<MfflSystemMessages> mfflSystemMessagesList = this.mfflSystemMessagesDao.getSystemMessages(sysUser.getId());
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(tableResponse);
        return returnBean;
    }

    @GetMapping(value = "/getSystemMessagesById")
    @ApiOperation(value = "消息中心-系统消息详情")
    public ReturnBean<MfflSystemMessages> getSystemMessagesById(
            @ApiParam(value = "系统消息id", name = "id", required = true) @RequestParam long id) {
        SysUser sysUser = UserUtil.getLoginUser();
        if (sysUser == null) {
            return new ReturnBean("201", "没有此用户");
        }
        MfflSystemMessages mfflSystemMessagesList = this.mfflSystemMessagesDao.getById(id);
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(mfflSystemMessagesList);
        return returnBean;
    }

    @GetMapping(value = "/updateMessageStatus")
    @ApiOperation(value = "消息中心-系统消息-修改系统消息状态")
    public ReturnBean<MfflSystemMessages> updateMessageStatus(
            @ApiParam(value = "系统消息id；传0所有消息已读", name = "id", required = true) @RequestParam long id) {
        SysUser sysUser = UserUtil.getLoginUser();
        if (sysUser == null) {
            return new ReturnBean("201", "没有此用户");
        }
        int status = 0;
        if (id == 0) {
            status = this.mfflSystemMessagesDao.updateMessageStatusByUserIdAll(sysUser.getId());
        } else {
            status = this.mfflSystemMessagesDao.updateMessageStatusById(id, sysUser.getId());
        }
        if (status == 0) {
            return new ReturnBean("201", "修改失败");
        }
        ReturnBean returnBean = new ReturnBean();
        return returnBean;
    }

}
